package com.example.aop;

import com.alibaba.nacos.common.utils.StringUtils;
import com.example.annotation.TargetDs;
import com.example.multidatasource.DataSourceThreadLocal;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;

/**
 * 数据源切面
 * @author long
 * @date 2023/12/8 9:40
 */
//@Aspect
//@Service
public class DataSourceAspect {

    /**
     * 方法执行前执行
     * @param ds
     * @throws Throwable
     */
    @Before(value = "@annotation(ds)",argNames = "ds")
    public void beforeService(TargetDs ds) throws Throwable {

        String dsName = ds.dsName();
        if(StringUtils.isNotBlank(dsName)){
            DataSourceThreadLocal.getThreadLocal().set(dsName);
        }
    }

    /**
     * 方法执行后执行,清除线程绑定的数据源key
     * @param ds
     * @throws Throwable
     */
    @After(value = "@annotation(ds)",argNames = "ds")
    public void afterService(TargetDs ds) throws Throwable {
        DataSourceThreadLocal.getThreadLocal().remove();
    }
}
